package com.gome.boot.common.util;

import com.gome.boot.common.enums.ExecutorTypeEnum;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Schedule工具类.
 *
 * @author baoxiufeng
 */
public class ScheduleUtils {
    /** 工具类单例实例 */
    private static volatile ScheduleUtils util = null;

    /** 默认固定数量的线程池大小 */
    private static final int EXECUTOR_THREAD_POOL_SIZE_DEFAULT = 10;

    /**
     * 私有构造方法.
     */
    private ScheduleUtils() {}

    /**
     * 获取工具类单例实例.
     *
     * @return 工具类单例实例对象
     */
    public static ScheduleUtils get() {
        if (util == null) {
            synchronized (ScheduleUtils.class) {
                if (util == null) {
                    util = new ScheduleUtils();
                }
            }
        }
        return util;
    }

    /**
     * 获取指定类型的线程池.
     *
     * @param type 线程池类型
     * @param size 固定数量的线程池的大小，默认值为10
     * @return 线程池实例对象
     */
    public <T extends ExecutorService> T getExecutor(ExecutorTypeEnum type, int...size) {
        switch (type) {
            case SINGLE: return (T) Executors.newSingleThreadExecutor();
            case SINGLE_SCHED: return (T) Executors.newSingleThreadScheduledExecutor();
            case CACHE: return (T) Executors.newCachedThreadPool();
            case FIX: return (T) Executors.newFixedThreadPool(
                    (size == null || size.length == 0 || size[0] <= 0) ? EXECUTOR_THREAD_POOL_SIZE_DEFAULT : size[0]);
            case FIX_SCHED: return (T) Executors.newScheduledThreadPool(
                    (size == null || size.length == 0 || size[0] <= 0) ? EXECUTOR_THREAD_POOL_SIZE_DEFAULT : size[0]);
            default: return (T) Executors.newSingleThreadExecutor();
        }
    }
}
